/**
 * @file models/scheduling.js
 * @author
 */
import { routerRedux } from 'dva/router';
import api from '../api';
import moment from 'moment'


export default {
	namespace: 'scheduling',
	state: {
		beginDate:'',
		endDate:'',
		jobName:'',
		currentpage:0,
		pagesize:0
	},
	subscriptions : {
		setup({dispatch, history}) {
			history.listen(({ pathname, query }) => {
				// 没有参数时，向后端请求数据，并且改变query
				if( pathname === '/systemMgt/operationMgt/taskMgt' ){
					dispatch({type: 'whetherRequest',payload:query,pathname})
				}
			})
		}
	},
	effects : {

		* whetherRequest({
				payload,pathname
			}, { put,select}) {

				const {
					beginDate,
					endDate,
					jobName,
					currentpage,
					pagesize
				}=payload
				if(beginDate||endDate){
					if(!(beginDate&&endDate)){
						yield put({
							type:'changeRouter',
							payload:{
								pathname
							}
						})
					}else{
						yield [
							put({
								type:'setState',
								payload
							}),
							put({
								type:'query',
								payload
							})
						]

					}
				}else{
					yield [
						put({
							type:'setState',
							payload:{
								beginDate:moment().subtract(1, 'M').add(1,'d').format('YYYY-MM-DD'),
								endDate:moment().format('YYYY-MM-DD'),
								currentpage:1,
								pagesize:15
							}
						}),
						put({
							type:'query',
							payload:{
								beginDate:moment().subtract(1, 'M').add(1,'d').format('YYYY-MM-DD'),
								endDate:moment().format('YYYY-MM-DD')
							}
						})
					]

				}
		},
		* query({payload}, {call, put,select}){
			const [
				count,
				task,
				day,
				fail,
				details
			] = yield [
				call(api.scheduling.getTotalSummary, payload),
				call(api.scheduling.getJobSummary, payload),
				call(api.scheduling.getEverydaySummary, payload),
				call(api.scheduling.getEverydayFails, payload),
				call(api.scheduling.getFailDetails, payload),
			]

			const jobList=fail.data.jobList

			const state=yield select(state=>state.scheduling)

			if(JSON.stringify(state.jobList)!=JSON.stringify(jobList)){
				yield put({type:'clearState'})
			}else{
				if(JSON.stringify(state.fail)!=JSON.stringify(fail.data.failRecords)){
					yield put({type:'clearState'})
				}
			}


			yield put({
				type: 'querySuccess',
				payload:{
					count:count.data,
					task:task.data,
					day:day.data,
					fail:fail.data.failRecords,
					jobList,
					details:details.data,
					page:details.page
				}
			});
		},
		* changeRouter({payload}, {put}){
			yield put(routerRedux.push(payload))
		}

	},
	reducers : {
		setState(state, {payload}) {
			return {
				...state,
				...payload
			}
		},

		clearState(state) {
			const {
				count,
				task,
				day,
				fail,
				jobList,
				details,
				...other
			}=state
      return{
				...other
			}
    },
		querySuccess(state, {payload}) {
			return {
				...state,
				...payload
			}
		}

	}
};
